package com.carrie.config.security;

import com.carrie.tools.LogUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.PrintWriter;

/**
 * @author XuHaiLong
 * @since 2025/4/16 00:48
 */
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException, java.io.IOException {
        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            try {
                username = jwtUtils.extractUsername(jwt);
            } catch (IllegalArgumentException e) {
                handleException(response, HttpStatus.BAD_REQUEST, "无法获取 JWT 令牌");
                return;
            } catch (ExpiredJwtException e) {
                handleException(response, HttpStatus.UNAUTHORIZED, "JWT 令牌已过期");
                return;
            }
        }
        // 检查豁免路径
        if (isExcludedPath(request.getRequestURI())) {
            LogUtils.info("这是豁免路径"+request.getRequestURI());
            chain.doFilter(request, response);
            return;
        }
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtUtils.validateToken(jwt, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            } else {
                LogUtils.error("无效的 JWT 令牌");
                handleException(response, HttpStatus.UNAUTHORIZED, "无效的 JWT 令牌");
                return;
            }
        }
        chain.doFilter(request, response);
    }
    private boolean isExcludedPath(String requestURI) {
        return  requestURI.equals("/**");
    }
    private void handleException(HttpServletResponse response, HttpStatus status, String message) throws IOException, java.io.IOException {
        response.setStatus(status.value());
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println("{\"error\": \"" + message + "\"}");
    }
}
